#!/bin/bash
set -e

source $(dirname $0)/version

cd $(dirname $0)/..

PROJECT=`basename "$PWD"`

case $(uname -m) in
  aarch64 | arm64)
    ARCH=arm64
    ;;
  x86_64)
    ARCH=amd64
    ;;
  *)
    echo "$(uname -a): unsupported architecture"
    exit 1
esac

if [ ! -x ./bin/longhorn ]; then
    ./scripts/build
fi

APIVERSION=`./bin/longhorn-instance-manager version --client-only|jq ".clientVersion.instanceManagerAPIVersion"`
TAG="v${APIVERSION}_`date -u +%Y%m%d`"
REPO=${REPO:-longhornio}
IMAGE=${REPO}/${PROJECT}:${TAG}

cp /usr/src/tgt/pkg/tgt_*.deb ./bin/

# update base image to get latest changes
BASE_IMAGE=`grep FROM package/Dockerfile  | awk '{print $2}'`
docker pull ${BASE_IMAGE}

docker build --build-arg ARCH=${ARCH} -t ${IMAGE} -f package/Dockerfile .

echo Built ${IMAGE}

echo ${IMAGE} > ./bin/latest_image
